<template>
  <div class="create_account">
    <!-- 页面主体 -->
    <v-main>
      <div class="page_name">
        <span class="title">创建账号</span>
      </div>
      <div class="account-form">
        <el-form :model="addForm" :rules="rules" size="mini" ref="addForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="账号" prop="user_name" class="form_width" ref="userName">
            <el-input v-model="addForm.user_name" :clearable="true" placeholder="6-18位英文数字组成"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="user_pass" class="form_width">
            <el-input type="password" v-model="addForm.user_pass" :clearable="true" placeholder="6-16位密码组成，区分大小写"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="verify_pass" class="form_width">
            <el-input type="password" v-model="addForm.verify_pass" :clearable="true" placeholder="再次输入密码"></el-input>
            <i class="el-icon-success check" v-show=" addForm.password && addForm.verifyPassword === addForm.password "></i>
          </el-form-item>
          <el-form-item label="联系方式" prop="phone" class="form_width">
            <el-input v-model="addForm.phone" :clearable="true" placeholder="请输入联系方式"></el-input>
          </el-form-item>
          <el-form-item label="员工姓名" prop="staff_name" class="form_width">
            <el-input v-model="addForm.staff_name" :clearable="true" placeholder="请输入员工姓名"></el-input>
          </el-form-item>
          <el-form-item label="角色" prop="role_ids_change">
            <el-select v-model="addForm.role_ids_change" @change="selectRole" placeholder="请选择角色">
              <el-option v-for="(item, index) in roleList" :label="item.display_name" :value="item.id" :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="权限" prop="rights">
            <div class="form_wrapper">
              <el-tree :data="roleRights" :default-expand-all="true"></el-tree>
            </div>
          </el-form-item>
          <el-form-item label="门店权限" prop="shop_ids">
            <div class="form_wrapper">
              <el-input v-model="addForm.shop_ids_change" v-show="false"></el-input>
              <el-table  ref="multipleTable"
                         size="mini"
                         :data="shopList"
                         tooltip-effect="dark"
                         style="width: 100%"
                         height="500"
                         @selection-change="handleSelectionChange">
              <el-table-column
                type="selection"
                width="55">
              </el-table-column>
              <el-table-column
                 label="门店列表"
                 width="600">
                 <template slot-scope="scope">{{ scope.row.name }}</template>
              </el-table-column>
             </el-table>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button class="create_btn" @click="onSubmit" :loading="addLoading">创建</el-button>
            <el-button @click="navToSettings">返回</el-button>
          </el-form-item>
        </el-form>
      </div>
    </v-main>
  </div>
</template>
<script type="text/ecmascript-6">
import { mapGetters } from 'vuex'
// components
import MainComp from '@/components/main'

// element-ui
import { Row, Col, Tabs, TabPane, Table, TableColumn, Button, Tree, Input, Form, FormItem, Select, Option, Message } from 'element-ui'
// API
import { APICreateAccount, APICanCreateRole, APICanCreate } from '@/api/settings.js'
import permissionTree from '../permissionTree'

// 表单验证正则
const validatePassword = (rule, value, callback) => {
  if (!value) {
    callback(new Error('密码不能为空'))
  } else if (!/^(?=.*[a-zA-Z])(?=.*\d)[\s\S]{6,16}$/.test(value)) {
    callback(new Error('请输入6-16位数字、英文组成的密码'))
  } else {
    callback()
  }
}

const validateTel = (rule, value, callback) => {
  if (!value) {
    callback(new Error('联系方式不能为空'))
  } else if (/(\D)/g.test(value) || value.length > 15) {
    callback(new Error('联系方式格式不正确'))
  } else {
    callback()
  }
}

const validateStaffName = (rule, value, callback) => {
  if (!value) {
    callback(new Error('姓名不能为空'))
  } else if (value.length < 2 || value.length > 8) {
    callback(new Error('姓名长度须在2-8个字符'))
  } else {
    callback()
  }
}

export default {
  name: 'CreateAccount',

  components: {
    // elementUI component
    elRow: Row,
    elCol: Col,
    elButton: Button,
    elTabs: Tabs,
    elTabPane: TabPane,
    elTable: Table,
    elTableColumn: TableColumn,
    elTree: Tree,
    elInput: Input,
    elFormItem: FormItem,
    elForm: Form,
    elSelect: Select,
    elOption: Option,
    // 项目自定义组件
    vMain: MainComp
  },

  created () {
    // init request
    this.APICanCreateRole()
    this.tabName = this.$route.query.tabName
    this.APICanCreate({userName: 'hahaha'})
  },

  data () {
    const validateUserName = (rule, value, callback) => {
      if (!value) {
        callback(new Error('账号不能为空'))
      } else if (!/^[a-zA-Z][a-zA-Z0-9]{5,17}$/.test(value)) {
        callback(new Error('格式不正确，账号由字母开头的6-18位英文数字组成'))
      } else {
        this.APICanCreate({userName: value})
          .then((res) => {
            if (res.data.exists === 1) {
              callback(new Error('账号已存在'))
            } else {
              callback()
            }
          })
      }
    }
    const validateVerifyPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.addForm.user_pass) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    const validateShopIds = (rule, value, callback) => {
      if (this.addForm.shop_ids_change === '') {
        callback(new Error('至少选择一家门店绑定'))
      } else {
        callback()
      }
    }
    return {
      tabName: null,
      addLoading: false,
      addForm: {
        user_name: '',
        user_pass: '',
        verify_pass: '',
        phone: '',
        staff_name: '',
        role_ids: null,
        role_ids_change: null,
        shop_ids: null,
        shop_ids_change: null
      },
      rules: {
        user_name: [
          { required: true, validator: validateUserName, trigger: 'blur' }
        ],
        user_pass: [
          { required: true, validator: validatePassword, trigger: 'blur' }
        ],
        verify_pass: [
          { required: true, validator: validateVerifyPassword, trigger: 'blur' }
        ],
        phone: [
          { required: true, validator: validateTel, trigger: 'blur' }
        ],
        staff_name: [
          { required: true, validator: validateStaffName, trigger: 'blur' }
        ],
        role_ids: [
          { required: true }
        ],
        shop_ids: [
          { required: true, validator: validateShopIds, trigger: 'change' }
        ]
      },
      roleList: [],
      multipleSelection: []
    }
  },

  computed: {
    ...mapGetters([
      'mallinfo'
    ]),
    roleRights () {
      let currentRole = this.roleList.filter((item) => item.id === this.addForm.role_ids_change)
      let currentRoleIds = currentRole && currentRole[0] ? currentRole[0]['rank'] : null
      if (currentRoleIds !== null && currentRoleIds !== undefined) {
        return permissionTree[currentRoleIds]['rights']
      } else {
        return []
      }
    },
    shopList () {
      return this.mallinfo.shopNameList
    }
  },

  methods: {
    handleSelectionChange (val) {
      this.multipleSelection = val
      this.addForm.shop_ids_change = (this.multipleSelection.map((item) => item.id)).join('-')
    },
    navToSettings () {
      this.$router.push({
        name: 'Settings',
        query: {
          tabName: this.tabName
        }
      })
    },
    // 提交表单
    onSubmit () {
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          this.addLoading = true
          this.addForm.role_ids = [this.addForm.role_ids_change]
          this.addForm.shop_ids = this.multipleSelection.map((item) => item.id)
          APICreateAccount(this.addForm).then((res) => {
            this.addLoading = false
            Message({
              message: '提交成功',
              type: 'success'
            })
          }).then(() => {
            this.$router.push({
              name: 'Settings',
              query: {
                tabName: this.tabName
              }
            })
          }).catch(() => {
            this.addLoading = false
          })
        } else {
          return false
        }
      })
    },
    selectRole (value) {
      this.addForm.role_ids = value
      this.addForm.role_ids_change = value
    },
    // ======= API ==================
    APICanCreateRole () {
      APICanCreateRole()
        .then((res) => {
          this.roleList = res.data.roles
          this.addForm.role_ids = res.data.roles[0]['id']
          this.addForm.role_ids_change = res.data.roles[0]['id']
        })
    },
    APICanCreate ({userName}) {
      return APICanCreate({userName})
    }
  }
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
  // scoped
  .create_account {
    width: 100%;
    height: auto;
    box-sizing: border-box;
    background-color: #FFF;
    padding: 20px;
    box-shadow: 0 2px 3px 0 rgba(0, 0, 0, .2);
    .page_name {
      margin-bottom: 20px;
      .title{
        font-weight: bold;
        font-size: 18px;
      }
    }
    .account-form {
      width: 1000px;
      .form_width {
        width: 400px;
      }
      .form_wrapper {
        border-radius: 4px;
        padding: 20px;
        border: 1px solid #dcdfe6;
      }
      .create_btn{
        background-color: #159bd5;
        color: #ffffff;
      }

    }
  }
</style>
